﻿using EventBus.Abstractions;
using LindDDDSample.SeedWork;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DbContext.Customization
{
    public class ApplicationContext : Microsoft.EntityFrameworkCore.DbContext
    {
        private readonly IEventBus _eventBus;
        public ApplicationContext(IEventBus eventBus)
        {
            _eventBus = eventBus;
        }
        public async Task<int> SaveEntitiesAsync()
        {
            var domainEntities = this.ChangeTracker.Entries<Entity>()
                .Where(e => e.Entity.DomainEvents != null && e.Entity.DomainEvents.Any()).ToList();

            var domainEvents = domainEntities.SelectMany(e => e.Entity.DomainEvents).ToList();

            domainEntities.ForEach(entity => entity.Entity.ClearDomainEvents());

            domainEvents.ForEach(@event =>
            {
                _eventBus.Publish(@event);
            });

            return await SaveChangesAsync();
        }
    }
}
